package ru.amse.jsynchro.net.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.Semaphore;

import ru.amse.jsynchro.logging.ILogger;
import ru.amse.jsynchro.net.Command;

public class SimpleServerThread extends ServerThread {
    private Semaphore semaphore;
    private String correctUserName;
    private String correctUserPassword;
    
    public SimpleServerThread(Socket socket, int threadNumber, ILogger logger,
            String localRoot, String userName, String userPassword) {
        super(socket, threadNumber, logger);
        myLocalRoot = localRoot;
        correctUserName = userName;
        correctUserPassword = userPassword;
        semaphore = new Semaphore(1);
    }
    
    
    public void run() {
        try {
            logger.info("serverthread: " + myThreadNumber + "  in run");
            socketOut = socket.getOutputStream();
            
            socketIn = socket.getInputStream();
            oout = new ObjectOutputStream(socketOut);
            oin = new ObjectInputStream(socketIn);
            if (!authenticate()) {
                logger.info("unknown user");
                return;
            }
            logger.info("serverthread - localRoot: " + myLocalRoot);
            
            boolean listen = true;
            while (listen) {
                System.out.println("waiting for comamnd");
               Command command = (Command) oin.readObject(); 
               logger.info("command: " + command.toString());
               listen = handleClientCommand(command);
            }
        } catch (IOException e) {
            logger.exception(e);
        } catch (ClassNotFoundException e) {
            logger.exception(e);
        }
        logger.info("releasing");
        semaphore.release();
    }
    
    private boolean authenticate() throws ClassNotFoundException, IOException {
        logger.info("authentication:");
        String userName = (String) oin.readObject(); 
        logger.info(userName);
        String userPassword = (String) oin.readObject();
        logger.info(userPassword);
        if (correctUserName.equals(userName) && correctUserPassword.equals(userPassword)) {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                logger.exception(e);
            }
            oout.writeObject("1");
            return true;
        }
        oout.writeObject("0");
        return false;
    }
}
